package com.yc.thread;

import java.util.ArrayList;
import java.util.List;

public class 生产者与消费者模式 {

    public static void main(String[] args) {
        Factory factory = new Factory();

        new Thread(()->{
            try {
                factory.produce();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    factory.consurme();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }

    }

}

class Factory{

    List<Object> store = new ArrayList<>();

    public synchronized void produce() throws InterruptedException {
        int i = 0;
        while(true){
            for (int j = 0; j < 10; j++) {
                Thread.sleep(100);
                Object o = "商品"+i++;
                store.add(o);
                System.out.println("生产："+o);
            }
            while(store.isEmpty()==false){
                // 通知其它线程进入同步代码块
                this.notifyAll();
                // wait 必须位于 synchronized 代码块中
                this.wait();
            }
        }
    }

    public void consurme() throws InterruptedException {
        while(true){
            synchronized (this){
                while(store.isEmpty()==true){
                    // 通知其它线程进入同步代码块
                    this.notifyAll();
                    // wait 必须位于 synchronized 代码块中
                    this.wait();
                }
                Object o = store.remove(0);
                Thread thread = Thread.currentThread();
                System.out.println(thread.getName()+ " 消费商品：" + o);
            }
            Thread.sleep(150);
        }
    }

}
